package br.com.jk.cotacaocompra.lista;

import br.com.jk.cliente.Cliente;
import br.com.jk.empresa.Empresa;
import br.com.jk.master.Master;
import br.com.jk.usuario.jtable.UsuarioJTableUtil;
import br.com.jk.util.JaxbUtil;
import br.com.jk.util.Util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;
import javax.xml.bind.JAXBException;

/**
 *
 * @author camilo
 */
public class CotacaoCompraJDialog extends javax.swing.JDialog {

  private static CotacaoCompraJDialog dialog;
  private static final long serialVersionUID = 1L;
  // Model da tabela
  CotacaoCompraTableModel cotacaoTm = new CotacaoCompraTableModel();
  CotacaoCompraRn rn = new CotacaoCompraRn();
//  atributos utilizados nas pesquisas externas
  private JTextField idPesquisa;
  private JTextField razaoPesquisa;
  private boolean modoConsultaExt;
  private String pathXml;

  public static CotacaoCompraJDialog getInstance(java.awt.Frame parent, boolean modal) {
    if (dialog == null) {
      dialog = new CotacaoCompraJDialog(parent, modal);
    }
    return dialog;
  }

  public static CotacaoCompraJDialog getInstance(java.awt.Frame parent, boolean modal, JTextField id,
          JTextField razao, Empresa empresa, Cliente cliente) {
    if (dialog == null) {
      dialog = new CotacaoCompraJDialog(parent, modal, id, razao);
    }
    return dialog;
  }

  /**
   * Creates new form FornecedorJDialog
   */
  private CotacaoCompraJDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    criaModel();

    setLocationRelativeTo(null);
    listar();
  }

  private CotacaoCompraJDialog(java.awt.Frame parent, boolean modal, JTextField id,
          JTextField razao) {
    super(parent, modal);
    this.idPesquisa = id;
    this.razaoPesquisa = razao;
    this.modoConsultaExt = true;

    initComponents();
    criaModel();

    setLocationRelativeTo(null);
  }

  private void criaModel() {
    jtCotacao.setModel(cotacaoTm);

    cotacaoTm.sorter(jtCotacao, cotacaoTm);

    UsuarioJTableUtil.alteraJTable(cotacaoTm, jtCotacao, "jtCotacao", Master.usuarioLogado);
  }

  /**
   * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
   * content of this method is always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    jtCotacao = new javax.swing.JTable();
    JtbMaster = new javax.swing.JToolBar();
    jbImportar = new javax.swing.JButton();
    jbExport = new javax.swing.JButton();
    JbExcluir = new javax.swing.JButton();
    JbRelatorio = new javax.swing.JButton();
    jbJTable = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Produtos da Cotação de Compra");
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosed(java.awt.event.WindowEvent evt) {
        formWindowClosed(evt);
      }
    });

    /*jtCotacao.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtCotacao.getSelectedRow();
        fControl.selecionado();
      }
    });

    jtCotacao.getColumnModel().getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtCotacao.getSelectedColumn();
        fControl.selecionado();
      }
    });*/
    jtCotacao.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
    jScrollPane1.setViewportView(jtCotacao);

    JtbMaster.setOrientation(javax.swing.SwingConstants.VERTICAL);
    JtbMaster.setRollover(true);

    jbImportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-save-hd.png"))); // NOI18N
    jbImportar.setToolTipText("Importa os produtos da cotação do MixDB para a tabela");
    jbImportar.setFocusable(false);
    jbImportar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jbImportar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jbImportar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbImportarActionPerformed(evt);
      }
    });
    JtbMaster.add(jbImportar);

    jbExport.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-export.png"))); // NOI18N
    jbExport.setToolTipText("Gera um arquivo XML para posterior importaçao");
    jbExport.setFocusable(false);
    jbExport.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jbExport.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jbExport.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbExportActionPerformed(evt);
      }
    });
    JtbMaster.add(jbExport);

    JbExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/archive-remove.png"))); // NOI18N
    JbExcluir.setToolTipText("Excluir");
    JbExcluir.setEnabled(false);
    JbExcluir.setFocusable(false);
    JbExcluir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbExcluir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbExcluir.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbExcluirActionPerformed(evt);
      }
    });
    JtbMaster.add(JbExcluir);

    JbRelatorio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/report.png"))); // NOI18N
    JbRelatorio.setToolTipText("Relatórios");
    JbRelatorio.setEnabled(false);
    JbRelatorio.setFocusable(false);
    JbRelatorio.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRelatorio.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRelatorio.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRelatorioActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRelatorio);

    jbJTable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/view-form-table.png"))); // NOI18N
    jbJTable.setToolTipText("Grava as informações da JTable");
    jbJTable.setFocusable(false);
    jbJTable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jbJTable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jbJTable.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbJTableActionPerformed(evt);
      }
    });
    JtbMaster.add(jbJTable);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 560, Short.MAX_VALUE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(JtbMaster, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 453, Short.MAX_VALUE)
          .addComponent(JtbMaster, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        .addGap(0, 0, Short.MAX_VALUE))
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void jbImportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbImportarActionPerformed
    Importar importar = new Importar();
    Thread th = new Thread(importar);
    th.start();
  }//GEN-LAST:event_jbImportarActionPerformed

  private void JbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbExcluirActionPerformed

  }//GEN-LAST:event_JbExcluirActionPerformed

  private void JbRelatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRelatorioActionPerformed
    try {
//      Master.setJpbStatusIndeterminate(true);
//      Master.setTextJlStatus("Gerando relatório...");
      ThreadReport thReport = new ThreadReport();
      thReport.start();

    } catch (Exception e) {
      Util.msgErro(e, "Erro ao gerar o relatório");
    }
  }//GEN-LAST:event_JbRelatorioActionPerformed

  private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    dialog = null;
  }//GEN-LAST:event_formWindowClosed

  private void jbJTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbJTableActionPerformed
    getLarguraJtBanco();
  }//GEN-LAST:event_jbJTableActionPerformed

  private void jbExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbExportActionPerformed
    JFileChooser dirXml = new JFileChooser();
    dirXml.setDialogTitle("Selecione o diretório");
    dirXml.setDialogType(JFileChooser.DIRECTORIES_ONLY);
    int retorno = dirXml.showOpenDialog(null);
    if (retorno == JFileChooser.APPROVE_OPTION) {
      pathXml = dirXml.getSelectedFile().getAbsolutePath();
      Exportar exportar = new Exportar();
      Thread th = new Thread(exportar);
      th.start();
    }

  }//GEN-LAST:event_jbExportActionPerformed

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(CotacaoCompraJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(CotacaoCompraJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(CotacaoCompraJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(CotacaoCompraJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        CotacaoCompraJDialog dialog = new CotacaoCompraJDialog(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
          @Override
          public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
          }
        });
        dialog.setVisible(true);
      }
    });
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton JbExcluir;
  private javax.swing.JButton JbRelatorio;
  private javax.swing.JToolBar JtbMaster;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JButton jbExport;
  private javax.swing.JButton jbImportar;
  private javax.swing.JButton jbJTable;
  private javax.swing.JTable jtCotacao;
  // End of variables declaration//GEN-END:variables
  Util.ValidaDigitacaoData docDataCadastro = new Util().new ValidaDigitacaoData();

  private void getLarguraJtBanco() {
    UsuarioJTableUtil.setUsuarioJTable(cotacaoTm, jtCotacao, "jtCotacao", Master.usuarioLogado);
  }

  public void selecionado() {
    /*int linha = jtCotacao.getSelectedRow();//grava a linha selecionada
     int linhaSel = jtCotacao.convertRowIndexToModel(linha);

     if (linhaSel >= 0) { // executa o procedimento se o JTable não estiver vazio
     int colunaSel = jtCotacao.getSelectedColumn(); //grava a coluna selecionada
     boolean pesq = control.setEnabledPesquisa(colunaSel); // Verifica as colunas que serão habilitadas para pesquisa
     jtfId.setText(cotacaoTm.getValueAt(linhaSel, CotacaoCompraTableModel.COLUNA_COD_OID).toString());
     jtfDataCad.setText(cotacaoTm.getValueAt(linhaSel, CotacaoCompraTableModel.COLUNA_COD_MARCA).toString());
     jcbxStatus.getModel().setSelectedItem(cotacaoTm.getValueAt(linhaSel, CotacaoCompraTableModel.COLUNA_COD_COMPLEMENTO).toString());
     jtfCodCotacao.setText(cotacaoTm.getValueAt(linhaSel, CotacaoCompraTableModel.COLUNA_COD_CODIGO).toString());
     jtfDescricao.setText(cotacaoTm.getValueAt(linhaSel, CotacaoCompraTableModel.COLUNA_COD_DESCRICAO).toString());
     jtfEmpresa.setText(cotacaoTm.getValueAt(linhaSel, CotacaoCompraTableModel.COLUNA_COD_EMPRESA).toString());
     jtfCliente.setText(cotacaoTm.getValueAt(linhaSel, CotacaoCompraTableModel.COLUNA_COD_QUANTIDADE).toString());
     jtfIdEmpresa.setText(cotacaoTm.getValueAt(linhaSel, CotacaoCompraTableModel.COLUNA_COD_ID_EMPRESA).toString());
     jtfIdCliente.setText(cotacaoTm.getValueAt(linhaSel, CotacaoCompraTableModel.COLUNA_COD_ID_CLIENTE).toString());

     control.modoConsulta = pesq;
     JbBuscar.setEnabled(pesq);
     }*/
  }

  public CotacaoCompra criaObjeto() {
    CotacaoCompra cotacao = new CotacaoCompra();
    /*cotacao.setStatus(Status.valueOf(jcbxStatus.getModel().getSelectedItem().toString()));
     cotacao.setCodCotacao(jtfCodCotacao.getText());
     cotacao.setDescricao(jtfDescricao.getText());
     cotacao.setDataCadastro(Util.formatDataSToD(jtfDataCad.getText()));
     try {
     Empresa empresa = control.carregaEmpresa(Integer.parseInt(jtfIdEmpresa.getText()));
     cotacao.setEmpresa(empresa);
     } catch (ControllerException e) {
     Util.msgErro("O Id da Empresa é inválido");
     }
     if (!jtfId.getText().isEmpty()) {
     cotacao.setId(Integer.parseInt(jtfId.getText()));
     }
     Cliente cliente = control.carregaCliente(Integer.parseInt(jtfIdCliente.getText()));
     cotacao.setCliente(cliente);*/

    return cotacao;
  }

  private void listar() {

  }

  private void limpar() {

  }

  public void setJtCotacaoTm(List<CotacaoCompra> ct) {
    removeAllJtable();
    if (!ct.isEmpty()) {
      cotacaoTm.adicionaLista(ct);
    }
  }

  public void setJtCotacaoTm(CotacaoCompra ct) {
    removeAllJtable();
    if (ct != null) {
      cotacaoTm.adiciona(ct);
    }
  }

  private void removeAllJtable() {
    while (cotacaoTm.getRowCount() > 0) {
      cotacaoTm.remove(0);
    }
  }

  /**
   * Determina quais os botões da barra de ferramentas ficará ativo
   *
   * @param novo
   * @param salvar
   * @param editar
   * @param cancelar
   * @param excluir
   */
  public void habilitaJb(Boolean novo, Boolean salvar, Boolean editar, Boolean cancelar,
          Boolean excluir) {
    jbImportar.setEnabled(salvar);
    JbExcluir.setEnabled(excluir);
  }

  private void selecionaRegistro() {
    int linha = jtCotacao.getSelectedRow();
    int linhaSel = jtCotacao.convertRowIndexToModel(linha);
    idPesquisa.setText(cotacaoTm.getValueAt(linhaSel, CotacaoCompraTableModel.COLUNA_COD_CODIGO).toString());
    razaoPesquisa.setText(cotacaoTm.getValueAt(linhaSel, CotacaoCompraTableModel.COLUNA_COD_DESCRICAO).toString());
    modoConsultaExt = false;
    this.dispose();
  }

  public class Importar implements Runnable {

    @Override
    public void run() {
      CotacaoCompraRn ccrn = new CotacaoCompraRn();
      List<CotacaoCompra> lst;
      lst = ccrn.listar();

      for (int i = 0; i < lst.size(); i++) {
        cotacaoTm.adiciona(lst.get(i));
      }
    }

  }

  public class Exportar implements Runnable {

    @Override
    public void run() {
      CotacaoAbs cotacao = new CotacaoAbs();
      try{
      JaxbUtil jax = new JaxbUtil();
      jax.gerarXml(cotacao, new File(pathXml));
      } catch (JAXBException | FileNotFoundException e){
        Util.msgErro(e, "Erro na exportação da cotação");
      }
    }

  }

  class ThreadReport extends Thread {

    @Override
    public void run() {
      try {
        rn.report();
      } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage());
      }
    }
  }
}
